# coding: utf-8

'''
author: runforever
'''

from rest_framework_jwt.views import JSONWebTokenAPIView
from .serializers import ZXJSONWebTokenSerializer

from rest_framework.response import Response
from rest_framework.decorators import action

from django.contrib.auth.models import User
from usercenter import models
from usercenter.common.errors import get_error_info, EMAIL_ERROR, ADMIN_EXIST_ERROR, SIMPLE_PASSWORD_ERROR
from usercenter.common.validators import validate_email

from rest_framework import viewsets
from usercenter.models import StaffProfile
from usercenter.common.request import get_trace_id
from .serializers import AdminRegisterSerializer

import logging
logger = logging.getLogger('userauth')


class ZXObtainJSONWebToken(JSONWebTokenAPIView):
    '''
    用户名密码登陆
    '''
    serializer_class = ZXJSONWebTokenSerializer


class AdminAuthViewSet(viewsets.GenericViewSet):
    """
    管理员注册
    """
    queryset = StaffProfile.objects.all()
    serializer_class = AdminRegisterSerializer
    permission_classes = ()

    @action(methods=['post'], detail=False)
    def reg(self, request, **kwargs):
        """
        管理员注册
        """
        self.get_serializer().run_validation(request.data)  # 验证输入

        ret = {'code': 0, 'message': ''}

        username = request.data.get('username', '').strip()
        email = request.data.get('email', '').strip()
        password = request.data.get('password', '').strip()
        if len(password) <= 5:
            ret.update(get_error_info(SIMPLE_PASSWORD_ERROR))  # 密码过于简单
            return Response(ret, 400)
        if not validate_email(email):
            ret.update(get_error_info(EMAIL_ERROR))  # email错误
            return Response(ret, 400)

        exists = models.StaffProfile.objects.filter(user__email=email).exists()
        if exists:  # email相同的用户存在
            ret.update(get_error_info(ADMIN_EXIST_ERROR))  # email相同的管理员存在
            return Response(ret)

        staffuser = models.StaffProfile.objects.filter(user__username=username).last()  # bug
        if staffuser:  # username相同的用户存在, 解决重名
            username1 = staffuser.user.username.split('_')
            count = 1 + int(username1[1]) if len(username1) > 1 else 1
            username = username + '_' + str(count)

        from django.db import DatabaseError, transaction

        try:
            with transaction.atomic():
                user = User.objects.create(email=email, username=username, is_active=False)
                user.set_password(password)
                user.save()
                staffuser = StaffProfile.objects.create(user=user)  # 创建职员
                logger.info('admin register: %s' % (request.data), extra={'trace_id': get_trace_id(request)})
        except DatabaseError as e:
            logger.error('admin register error: %s; \n %s ' % (request.data, e), extra={'trace_id': get_trace_id(request)})

        assert staffuser.id, '管理员注册失败'

        return Response(ret)
